Friday, October 25, 2024

C# base Keyword Explained

In C#, the base keyword is used to refer to the immediate base class of the current derived class. It allows you to access members (fields, properties, methods) of the base class within a derived class when there is a hierarchy of inheritance.

Here are the main uses of the base keyword in C#:

1. Calling Base Class Constructors:
   The base keyword is used to call a constructor of the base class from the constructor of a derived class. This is typically done to initialize the members of the base class before initializing the members of the derived class.
   class BaseClass
   {
       public BaseClass(int value)
       {
           // Initialize base class members using value
       }
   }

   class DerivedClass : BaseClass
   {
       public DerivedClass(int value) : base(value)
       {
           // Initialize derived class members
       }
   }

2. Accessing Base Class Members:
   The base keyword is used to access members (fields, properties, and methods) defined in the base class from the context of the derived class.
   class BaseClass
   {
       public void Display()
       {
           Console.WriteLine("Displaying from BaseClass");
       }
   }

   class DerivedClass : BaseClass
   {
       public void DisplayFromDerived()
       {
           Console.WriteLine("Displaying from DerivedClass");
           base.Display();  // Calls the Display method of the base class
       }
   }

In the above example, base.Display() calls the Display method of the base class.

By using the base keyword, you can handle situations where you need to access or invoke functionality defined in the base class within the context of a derived class.

No comments:

Post a Comment

Hot Topics